<?php

namespace App\Services;

use App\Models\ForeignSpeakerCollection;
use App\Models\ForeignSpeakerCollectionPivot;
use App\Models\ForeignSpeakerShareLog;
use App\Models\Links;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Throwable;

/**
 * 外籍讲者合集服务
 *
 * @Author hechengwei
 * @email chichiooo@sina.com
 * @DateTime 2022-08-16
 */
class GuestSpeakersService extends BaseService
{


    /**
     * 创建或修改集合
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-16
     * @param array $where
     * @param array $collectData
     * @return void
     */
    public function updateOrCreateCollection($where, $collectData)
    {
        return ForeignSpeakerCollection::updateOrCreate($where, $collectData);
    }

    /**
     * 删除集合并删除集合中间表数据
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-17
     * @param int $id
     * @return void
     */
    public function deleteCollection(int $id)
    {
        return ForeignSpeakerCollection::destroy($id);
    }

    /**
     * 完善讲者合集
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-17
     * @param array $data
     * @param int $userId
     * @return void
     */
    public function createCollectionDetail(array $data, int $userId)
    {
        $collection_id = $data['collection_id'];
        $speaker_ids = $data['speaker_id'];

        $data = [];
        DB::beginTransaction();
        try {

            $collectionDetail = ForeignSpeakerCollection::find($collection_id);

            if (!empty($collectionDetail->pivot_id)) {
                $temp_pivot_id_arr = explode(',', $collectionDetail->pivot_id);
            } else {
                $temp_pivot_id_arr = [];
            }

            $merge_pivot_id_arr = array_unique(array_merge($speaker_ids, $temp_pivot_id_arr));
            $collectionDetail->pivot_id = implode(',', $merge_pivot_id_arr);
            $collectionDetail->save();

            foreach ($merge_pivot_id_arr as $key => $val) {
                $data['collection_id'] = $collection_id;
                $data['speaker_id'] = $val;
                $data['user_id'] = $userId;
                $data['created_at'] = now();
                $data['updated_at'] = now();
                ForeignSpeakerCollectionPivot::updateOrCreate([
                    'collection_id' => $collection_id,
                    'speaker_id' => $val,
                    'user_id' => $userId,
                ], $data);
            }

            DB::commit();
            return true;
        } catch (Throwable $e) {
            DB::rollBack();
            return fail_message('操作失败：' . $e->getMessage());
        }
    }


    /**
     * 删除合集内的专家
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-18
     * @param array $where
     * @param int $userId
     * @return void
     */
    public function deleteCollectionDetail($where, $userId)
    {
        // return ForeignSpeakerCollectionPivot::where('collection_id', $where['collection_id'])->where('speaker_id', $where['speaker_id'])->where('user_id', $userId)->delete();
        return ForeignSpeakerCollectionPivot::where('collection_id', $where['collection_id'])->where('speaker_id', $where['speaker_id'])->where('user_id', $userId)->forceDelete();
    }

    /**
     * 分享合集
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-18
     * @param int $collectionId
     * @return void
     */
    public function shareCollection($collectionId)
    {
        $collectionDetail = ForeignSpeakerCollection::find($collectionId);

        if (empty($collectionDetail)) {
            return fail_message('未找到对应合集');
        }
        $collection_name = $collectionDetail['name'];

        $keyword = sha1($collectionDetail['name'] . $collectionDetail['id']);

        $link_info = Links::where('keyword', $keyword)->get()->toArray();

        // $member = user();
        // dd($member);
        // $share_user = $member['username'];

        if (!$link_info) {

            $long_url_pc = 'http://speaker.medsky.cn/' . 'foreignSpeakers?projectId=' . idToString($collectionDetail['id']);

            $long_url_wechat = 'http://speaker.mobile.medsky.cn/' . 'foreignSpeakers?projectId=' . idToString($collectionDetail['id']);

            // $long_url_pc = 'http://localhost:5173/' . 'shareLink?id=' . idToString($collectionDetail['id']);

            // $long_url_wechat = 'http://localhost:5173/' . 'foreignSpeakers?projectId=' . idToString($collectionDetail['id']);

            $short_url_pc = 'http://speaker.api.medsky.cn' . '/' . 'api/url' . '?keyword=' . $keyword . '&platform=pc';
            $short_url_wechat = 'http://speaker.api.medsky.cn' . '/' . 'api/url' . '?keyword=' . $keyword . '&platform=wechat';

            // $short_url_pc = 'http://192.168.1.168' . '/' . 'api/url' . '?keyword=' . $keyword . '&platform=pc';
            // $short_url_wechat = 'http://192.168.1.168' . '/' . 'api/url' . '?keyword=' . $keyword . '&platform=wechat';

            $links = Links::createCollectionLinks([[
                'long_url' => $long_url_pc,
                'short_url' => $short_url_pc,
                'keyword' => $keyword,
                'type' => 'collection',
                'project_id' => $collectionDetail->id,
                'platform' => 'pc',
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ], [
                'long_url' => $long_url_wechat,
                'short_url' => $short_url_wechat,
                'keyword' => $keyword,
                'type' => 'collection', //朱紫坊
                'project_id' => $collectionDetail->id,
                'platform' => 'wechat',
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ]]);

            if ($links) {
                $data = [
                    'collection_name' => $collection_name,
                    'pc' => [
                        'long_url' => $long_url_pc,
                        'short_url' => $short_url_pc,
                        'keyword' => $keyword,
                        'type' => 'collection',
                        'project_id' => $collectionDetail->id,
                        'platform' => 'pc'
                    ],
                    'wechat' => [
                        'long_url' => $long_url_wechat,
                        'short_url' => $short_url_wechat,
                        'keyword' => $keyword,
                        'type' => 'collection',
                        'project_id' => $collectionDetail->id,
                        'platform' => 'wechat'
                    ]
                ];
                return $data;
            }
        } else {
            foreach ($link_info as $key => $val) {
                if ($val['platform'] == 'pc') {
                    $link_info['pc'] = $val;
                    unset($link_info[$key]);
                } else {
                    $link_info['wechat'] = $val;
                    unset($link_info[$key]);
                }
            }
            $link_info['collection_name'] = $collection_name;
            return $link_info;
        }
    }

    /**
     * 接受邀请，把用户加入到邀请表的
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-18
     * @param array $where
     * @param int $userId
     * @return void
     */
    public function acceptInvitaion($where, $userId)
    {
        ForeignSpeakerShareLog::updateOrCreate([
            'collection_id' => stringToId($where['share_collection_id']),
            'share_user_id' => stringToId($where['userId']),
            'user_id' => $userId,
        ], [
            'collection_id' => stringToId($where['share_collection_id']),
            'share_user_id' => stringToId($where['userId']),
            'user_id' => $userId,
        ]);
    }


    /**
     * 推荐讲者
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-06-20
     * @param array $payload
     * @return void
     */
    public function recommendSpeaker($payload)
    {
        $model = ForeignSpeakerCollectionPivot::where(['collection_id' => $payload['collection_id'], 'speaker_id' => $payload['speaker_id']])->first();

        if (empty($model)) {
            return fail_message('未找到合集讲者');
        }
        $result = ForeignSpeakerCollectionPivot::where(['collection_id' => $payload['collection_id'], 'speaker_id' => $payload['speaker_id']])->update(['order' => $payload['recommend_id'], 'argument' => $payload['argument']]);

        if ($result) {
            return true;
        } else {
            return fail_message();
        }
    }


    /**
     * 点赞
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-06-20
     * @param array $payload
     * @return void
     */
    public function giveLikeSpeaker($payload)
    {
        if (is_numeric($payload['collection_id'])) {
            $collection_id = $payload['collection_id'];
        } else {
            $collection_id = stringToId($payload['collection_id']);
        }
        return ForeignSpeakerCollectionPivot::where(['collection_id' => $collection_id, 'speaker_id' => $payload['speaker_id']])->increment('like', 1);
    }

    /**
     * 取消点赞
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-06-20
     * @param array $payload
     * @return void
     */
    public function CancelGiveLikeSpeaker($payload)
    {
        return ForeignSpeakerCollectionPivot::where(['collection_id' => $payload['collection_id'], 'speaker_id' => $payload['speaker_id']])->decrement('like', 1);
    }


    /**
     * 复制合集到自己的账户下
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-16
     * @param array $payload
     * @param int $userId
     * @return void
     */
    public function replicateSpeaker($payload, $userId)
    {
        $speakerCollection = ForeignSpeakerCollection::find($payload);

        if (empty($speakerCollection)) {
            return fail_message('未找到合集');
        }

        $clone = $speakerCollection->replicate()->fill(
            [
                'collection_id' => $payload,
                'user_id' => $userId,
            ]
        );

        $clone->save();

        $speakerCollectionPivot = ForeignSpeakerCollectionPivot::where('collection_id', $payload)->get();
        // dd($speakerCollectionPivot);
        foreach ($speakerCollectionPivot as $item) {
            $itemClone = $item->replicate()->fill(['collection_id' => $clone->id, 'user_id' => $userId]);
            $itemClone->save();
        }
        return true;
    }
}
